import 'package:flutter/material.dart';
import 'package:gim_plugin/gim_plugin.dart';
import 'package:gim_plugin_example/sdk/gim_sdk.dart';
import 'package:gim_plugin_example/service/user_svc.dart';

class TabConversationStore extends ChangeNotifier {
  List<ConversationInfo> list = [];
  int pageNo = 1;
  int pageSize = 20;
  int notifyData = 0;

  Future<void> updateListIndex(ConversationInfo conv) async {
    var dto = await UserSvc.getConversationInfos(uids: [conv.toUid!]);
    if (dto == null) {
      conv.nickname = '${conv.id}';
      conv.avatar = 'images/default_avatar.png';
    } else {
      conv.nickname = dto.userInfos![conv.toUid!]!.nickname!;
      conv.avatar = dto.userInfos![conv.toUid!]!.avatar!;
    }
    if (list.isEmpty) {
      list.add(conv);
    } else if (list.length == 1) {
      list.clear();
      list.add(conv);
    } else {
      for (int i = 0; i < list.length; i++) {
        if (list[i].id == conv.id) {
          list.removeAt(i);
          break;
        }
      }
      if (conv.markTop ?? false) {
        list.insert(0, conv);
      } else {
        for (int j = 0; j < list.length; j++) {
          if (!(list[j].markTop ?? false)) {
            list.insert(j, conv);
            break;
          }
        }
      }
    }
    notifyData = DateTime.now().microsecondsSinceEpoch;
    notifyListeners();
  }

  Future<void> getList({bool refresh = false}) async {
    if (refresh) {
      pageNo = 1;
    }
    var dto = await gimSdk.gim.getConversationList(pageNo: pageNo, pageSize: pageSize);
    if (dto == null) return;
    notifyData = DateTime.now().microsecondsSinceEpoch;
    if (dto.arr!.isNotEmpty) {
      List<String> uids = [];
      for (int i = 0;i < dto.arr!.length;i++) {
        uids.add(dto.arr![i].toUid!);
      }

      var infos = await UserSvc.getConversationInfos(uids: uids);
      for(int i = 0;i < dto.arr!.length;i++) {
        if (infos == null) {
          dto.arr![i].nickname = '${dto.arr![i].id}';
          dto.arr![i].avatar =     'images/default_avatar.png';
        } else {
          dto.arr![i].nickname = infos.userInfos![dto.arr![i].toUid!]!.nickname!;
          dto.arr![i].avatar = infos.userInfos![dto.arr![i].toUid!]!.avatar!;
        }
      }

      if (refresh) {
        list = dto.arr!;
      } else {
        list.addAll(dto.arr!);
      }
      pageNo++;
      notifyListeners();
    } else if (refresh) {
      list = [];
      notifyListeners();
    }
  }
}
